package models

import (
	"strconv"
	"strings"

	"github.com/beego/beego/v2/client/orm"
)

// VenuePackage 场地预约套餐模型
type VenuePackage struct {
	BaseModel
	Name        string  `orm:"size(100)" json:"name"`               // 套餐名称
	Description string  `orm:"size(500)" json:"description"`        // 套餐描述
	Price       float64 `orm:"digits(10);decimals(2)" json:"price"` // 套餐价格
	Duration    int     `orm:"default(1)" json:"duration"`          // 使用时长(小时)
	Stores      string  `orm:"size(1000)" json:"stores"`            // 适用门店ID列表，JSON格式存储
	Venues            string `orm:"size(1000)" json:"venues"`                       // 适用场地ID列表，JSON格式存储
	AvailableTimes    string `orm:"type(text)" json:"available_times,omitempty"`      // 可用时间段, JSON格式, e.g., [{"start":"08:00","end":"12:00"}]
	AvailableWeekdays string `orm:"size(255)" json:"available_weekdays,omitempty"` // 可用星期, JSON格式, e.g., [1,2,3,4,5]
	Status            int8   `orm:"default(1)" json:"status"`                         // 状态：1-启用，0-禁用
	SortOrder         int    `orm:"default(0)" json:"sort_order"`                     // 排序
}

// TableName 设置表名
func (p *VenuePackage) TableName() string {
	return "ss_venue_package"
}

// GetVenuePackageById 根据ID获取场地预约套餐信息
func GetVenuePackageById(id int64) (*VenuePackage, error) {
	packa := &VenuePackage{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(packa)
	return packa, err
}

// GetVenuePackageList 获取场地预约套餐列表
func GetVenuePackageList(page, pageSize int, filters map[string]interface{}) ([]*VenuePackage, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(VenuePackage))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var packages []*VenuePackage
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&packages)

	return packages, total, err
}

// CreateVenuePackage 创建场地预约套餐
func CreateVenuePackage(pack *VenuePackage) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(pack)
	return id, err
}

// UpdateVenuePackage 更新场地预约套餐信息
func UpdateVenuePackage(pack *VenuePackage, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(pack, fields...)
	return err
}

// DeleteVenuePackage 删除场地预约套餐（软删除）
func DeleteVenuePackage(id int64) error {
	o := orm.NewOrm()
	pack := &VenuePackage{BaseModel: BaseModel{Id: id}}
	if err := o.Read(pack); err != nil {
		return err
	}

	pack.IsDeleted = 1
	_, err := o.Update(pack, "IsDeleted")
	return err
}

// GetVenuePackagesByVenueId 根据场地ID获取套餐列表
func GetVenuePackagesByVenueId(venueId int64) ([]*VenuePackage, error) {
	o := orm.NewOrm()
	var packages []*VenuePackage

	// 构建JSON匹配模式：场地ID可能在数组中的任何位置
	// 例如：[1,2,3], [1], [1,3,5] 等格式
	venueIdStr := strconv.FormatInt(venueId, 10)

	// 使用多种匹配模式搜索JSON数组中的元素
	patterns := []string{
		"[" + venueIdStr + "]",     // 精确匹配 [1]
		"[" + venueIdStr + ",",     // 开头位置 [1,2,3]
		"," + venueIdStr + ",",     // 中间位置 [2,1,3]
		"," + venueIdStr + "]",     // 结尾位置 [2,3,1]
		"[\"" + venueIdStr + "\"]", // 字符串形式 ["1"]
		"[\"" + venueIdStr + "\",", // 字符串开头 ["1",...]
		",\"" + venueIdStr + "\",", // 字符串中间 [...,"1",...]
		",\"" + venueIdStr + "\"]", // 字符串结尾 [...,"1"]
	}

	// 构建查询条件
	var conditions []string
	var params []interface{}

	for _, pattern := range patterns {
		conditions = append(conditions, "venues LIKE ?")
		params = append(params, "%"+pattern+"%")
	}

	// 添加查询所有场地的套餐
	conditions = append(conditions, "venues = '[]'")
	conditions = append(conditions, "venues = ''")

	// 构建SQL查询语句
	sql := "SELECT * FROM ss_venue_package WHERE is_deleted = 0 AND status = 1 AND (" +
		strings.Join(conditions, " OR ") +
		") ORDER BY sort_order, id DESC"

	_, err := o.Raw(sql, params...).QueryRows(&packages)

	return packages, err
}
